package com.feeyin.radar.crm.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;

import com.feeyin.radar.commons.BigDecimalPropertyEditor;
import com.feeyin.radar.commons.DatePropertyEditor;
import com.feeyin.radar.commons.Page;
import com.feeyin.radar.commons.StringUtils;
import com.feeyin.radar.crm.form.BackCostForm;
import com.feeyin.radar.crm.form.BackCostNewForm;
import com.feeyin.radar.crm.form.ExportBackCostForm;
import com.feeyin.radar.crm.model.BackCost;
import com.feeyin.radar.crm.model.BackCostNew;
import com.feeyin.radar.crm.model.ContractCase;
import com.feeyin.radar.crm.service.ContractBackCostService;
import com.feeyin.radar.crm.service.ContractService;

public class ContractBackCostController extends MultiActionController
{
  private ContractBackCostService contractBackCostService;
  private ContractService contractService;
  private String backCostManage;
  private String addBackCost;
  private String depBackCostManage;
  private String exportBackCost;
  private String updateBackCost;
  private String insertBackCost;
  private String backCostNewList;
  private String updateBackCostNew;

  
  public String getUpdateBackCostNew() {
	return updateBackCostNew;
}

public void setUpdateBackCostNew(String updateBackCostNew) {
	this.updateBackCostNew = updateBackCostNew;
}

public String getBackCostNewList() {
	return backCostNewList;
}

public void setBackCostNewList(String backCostNewList) {
	this.backCostNewList = backCostNewList;
}

public String getInsertBackCost() {
	return insertBackCost;
}

public void setInsertBackCost(String insertBackCost) {
	this.insertBackCost = insertBackCost;
}

public ContractBackCostService getContractBackCostService()
  {
    return this.contractBackCostService;
  }

  public void setContractBackCostService(ContractBackCostService contractBackCostService)
  {
    this.contractBackCostService = contractBackCostService;
  }

  public ContractService getContractService() {
    return this.contractService;
  }

  public void setContractService(ContractService contractService) {
    this.contractService = contractService;
  }

  public String getBackCostManage() {
    return this.backCostManage;
  }

  public void setBackCostManage(String backCostManage) {
    this.backCostManage = backCostManage;
  }

  public String getAddBackCost() {
    return this.addBackCost;
  }

  public void setAddBackCost(String addBackCost) {
    this.addBackCost = addBackCost;
  }

  public String getDepBackCostManage() {
    return this.depBackCostManage;
  }

  public void setDepBackCostManage(String depBackCostManage) {
    this.depBackCostManage = depBackCostManage;
  }

  public String getExportBackCost() {
    return this.exportBackCost;
  }

  public void setExportBackCost(String exportBackCost) {
    this.exportBackCost = exportBackCost;
  }

  public String getUpdateBackCost() {
    return this.updateBackCost;
  }

  public void setUpdateBackCost(String updateBackCost) {
    this.updateBackCost = updateBackCost;
  }

  public ModelAndView display(HttpServletRequest request, HttpServletResponse response)
  {
    Map model = new HashMap();
    model.put("result", request.getParameter("result"));
    Integer userId = (Integer)request.getSession().getAttribute("userId");

    String sFlag = request.getParameter("sFlag");
    String customerName = "";
    if ((!StringUtils.isEmpty(sFlag)) && ("1".equals(sFlag))) {
      customerName = request.getParameter("customerName");
    }
    model.put("sFlag", sFlag);
    model.put("customerName", customerName);

    Page page = new Page();
    page.getPageList(this.contractBackCostService.getPageMyContractsCount(null, customerName, userId).intValue(), null, request);
    model.put("contracts", this.contractBackCostService.getPageMyContracts(null, customerName, userId, page));
    return new ModelAndView(getBackCostManage(), model);
  }

  public ModelAndView deptBackCostManage(HttpServletRequest request, HttpServletResponse response)
  {
    Map model = new HashMap();
    model.put("result", request.getParameter("result"));
    Integer userId = (Integer)request.getSession().getAttribute("userId");
    String isAllBackCost = (String)request.getSession().getAttribute("isViewAllBackCost");
    if ((StringUtils.isEmpty(isAllBackCost)) || (!"1".equals(isAllBackCost))) {
      isAllBackCost = "2";
    }

    String sFlag = request.getParameter("sFlag");
    String customerName = "";
    if ((!StringUtils.isEmpty(sFlag)) && ("1".equals(sFlag))) {
      customerName = request.getParameter("customerName");
    }
    model.put("sFlag", sFlag);
    model.put("customerName", customerName);

    Page page = new Page();
    page.getPageList(this.contractBackCostService.getPageMyContractsCount(isAllBackCost, customerName, userId).intValue(), null, request);
    model.put("contracts", this.contractBackCostService.getPageMyContracts(isAllBackCost, customerName, userId, page));

    return new ModelAndView(getDepBackCostManage(), model);
  }

  public ModelAndView preAddBackCost(HttpServletRequest request, HttpServletResponse response)
  {
    Map model = new HashMap();
    model.put("sign", request.getParameter("sign"));

    String id = request.getParameter("id");
    if (!StringUtils.isEmpty(id)) {
      model.put("contract", this.contractService.getContractById(Integer.valueOf(Integer.parseInt(id))));

      model.put("ranges", this.contractBackCostService.getBackCostDictionaryRanges());
    }
    return new ModelAndView(getAddBackCost(), model);
  }

  public ModelAndView addBackCost(HttpServletRequest request, HttpServletResponse response, BackCostForm backCostForm)
  {
    boolean result = false;
    int success = 0;
    String sign = request.getParameter("sign");

    if (backCostForm != null) {
      result = this.contractBackCostService.insertBackCost(backCostForm);
      if (result) success = 1;
    }

    if ((!StringUtils.isEmpty(sign)) && ("2".equals(sign))) {
      return new ModelAndView(new RedirectView("./contractBackCost.do?action=deptBackCostManage&result=" + success));
    }
    return new ModelAndView(new RedirectView("./contractBackCost.do?action=display&result=" + success));
  }

  public ModelAndView preUpdateBackCost(HttpServletRequest request, HttpServletResponse response)
  {
    Map model = new HashMap();
    model.put("sign", request.getParameter("sign"));

    String id = request.getParameter("id");
    if (!StringUtils.isEmpty(id)) {
      int size = this.contractBackCostService.getBackCosts(Integer.valueOf(Integer.parseInt(id))).size();
      if (size > 0) {
        BackCost bc = (BackCost)this.contractBackCostService.getBackCosts(Integer.valueOf(Integer.parseInt(id))).get(0);
        model.put("BC", bc);
      }
      List list = new ArrayList();
      list.add(Integer.valueOf(size));
      for (int i = 0; i < 5; i++) {
        size++;
        System.out.print(size);
        list.add(Integer.valueOf(size));
      }

      model.put("contract", this.contractService.getContractById(Integer.valueOf(Integer.parseInt(id))));
      model.put("backCosts", this.contractBackCostService.getBackCosts(Integer.valueOf(Integer.parseInt(id))));
      model.put("indexs1", list.get(0));
      model.put("indexs2", list.get(1));
      model.put("indexs3", list.get(2));
      model.put("ranges", this.contractBackCostService.getBackCostDictionaryRanges());
    }
    return new ModelAndView(getUpdateBackCost(), model);
  }
  
  public ModelAndView preInsertBackCost(HttpServletRequest request, HttpServletResponse response)
  {
    Map model = new HashMap();
    model.put("sign", request.getParameter("sign"));

    String id = request.getParameter("id");
    if (!StringUtils.isEmpty(id)) {
      List<ContractCase> contractCaseList = this.contractService.getContractCasesByContractCode(id);
      Double caseRemain = 0.0;
      for(ContractCase cc : contractCaseList)
      {
    	  caseRemain += cc.getOfficialCost() + cc.getOperationCost() + cc.getProxyCost();
      }
      model.put("contractId", id);
      model.put("caseRemain", caseRemain);
      model.put("contractCases", this.contractService.getContractCasesByContractCode(id));
      model.put("ranges", this.contractBackCostService.getBackCostDictionaryRanges());
    }
    return new ModelAndView(getInsertBackCost(), model);
  } 
  
  public ModelAndView insertBackCost(HttpServletRequest request, HttpServletResponse response, BackCostNewForm backCostNewForm)
  {
    Map model = new HashMap();
    model.put("sign", request.getParameter("sign"));
    
    Integer success = 0;
    String costNum = backCostNewForm.getCostNum();
    if(costNum != null && !("").equals(costNum))
    {
        Boolean isDuplicate = contractBackCostService.isDuplicateBackCostNew(costNum);
        if(!isDuplicate)
        {
            Boolean result = contractBackCostService.insertBackCostNew(backCostNewForm);
            
            if(result == true)
            	success = 1;
            else
            	success = 0;         	
        }
  	
    }

    return new ModelAndView(new RedirectView("./contractBackCost.do?action=display&result=" + success));
  }
  
  public ModelAndView preUpdateBackCostMge(HttpServletRequest request, HttpServletResponse response)
  {
	    Map model = new HashMap();
	    model.put("sign", request.getParameter("sign"));
	    String id = request.getParameter("id");	  
	    
	    List<BackCostNew> backCostList = contractBackCostService.getBackCostNewListByContractId(id);
	    model.put("backCostList", backCostList);
	    model.put("ranges", this.contractBackCostService.getBackCostDictionaryRanges());
	    return new ModelAndView(getBackCostNewList(), model);
  }

  public ModelAndView preUpdateBackCostNew(HttpServletRequest request, HttpServletResponse response)
  {
    Map model = new HashMap();
    model.put("sign", request.getParameter("sign"));

    String backCostId = request.getParameter("id");
    if (!StringUtils.isEmpty(backCostId)) {
    	BackCostNew backCostNew = this.contractBackCostService.getBackCostNewById(backCostId);
    	
      List<ContractCase> contractCaseList = this.contractService.getContractCasesByContractCode(backCostNew.getContractId());
      Double caseRemain = 0.0;
      for(ContractCase cc : contractCaseList)
      {
    	  caseRemain += cc.getOfficialCost() + cc.getOperationCost() + cc.getProxyCost();
      }
      
//      List<ContractCase> ccList = this.contractService.getContractCasesByContractCode(backCostNew.getContractId());

      model.put("contractId", backCostNew.getContractId());
      model.put("caseRemain", caseRemain);
      model.put("backCostNew", backCostNew);
      model.put("ranges", this.contractBackCostService.getBackCostDictionaryRanges());
    }
    return new ModelAndView(this.getUpdateBackCostNew(), model);
  } 
  
  public ModelAndView updateBackCostNew(HttpServletRequest request, HttpServletResponse response, BackCostNewForm backCostNewForm)
  {
	    Map model = new HashMap();
	    model.put("sign", request.getParameter("sign"));
	    
	    Integer success = 0;
        Boolean result = contractBackCostService.updateBackCostNew(backCostNewForm);
        if(result == true)
        	success = 1;
        else
        	success = 0;         	
	  
	  return new ModelAndView(new RedirectView("./contractBackCost.do?action=display&result=" + success)); 
  }
    
  
  public ModelAndView updateBackCost(HttpServletRequest request, HttpServletResponse response, BackCostForm backCostForm)
  {
    boolean result = false;
    int success = 0;
    String sign = request.getParameter("sign");

    if (backCostForm != null) {
      result = this.contractBackCostService.updateBackCost(backCostForm);
      if (result) success = 2;
    }

    if (!StringUtils.isEmpty(sign)) {
      if ("1".equals(sign))
        return new ModelAndView(new RedirectView("./contractBackCost.do?action=display&result=" + success));
      if ("2".equals(sign))
        return new ModelAndView(new RedirectView("./contractBackCost.do?action=deptBackCostManage&result=" + success));
      if ("3".equals(sign))
        return new ModelAndView(new RedirectView("./contract.do?action=preDeptContract&result=" + success));
      if ("4".equals(sign)) {
        return new ModelAndView(new RedirectView("./contract.do?action=preClosedContract&result=" + success));
      }
    }
    return new ModelAndView(new RedirectView("./contractBackCost.do?action=display&result=" + success));
  }

  public ModelAndView preExportBackCost(HttpServletRequest request, HttpServletResponse response)
  {
    Map model = new HashMap();
    model.put("result", request.getParameter("result"));
    String sign = request.getParameter("sign");
    model.put("sign", sign);
    Integer userId = (Integer)request.getSession().getAttribute("userId");
    String isAllBackCost = (String)request.getSession().getAttribute("isViewAllBackCost");
    model.put("users", this.contractBackCostService.getUsers(isAllBackCost, sign, userId));
    return new ModelAndView(getExportBackCost(), model);
  }

  public ModelAndView exportBackCost(HttpServletRequest request, HttpServletResponse response, ExportBackCostForm exportBackCostForm)
  {
    String sign = request.getParameter("sign");
    Integer userId = (Integer)request.getSession().getAttribute("userId");
    String isAllBackCost = (String)request.getSession().getAttribute("isViewAllBackCost");
    String[] userIds = request.getParameterValues("id");
    boolean result = false;
    int success = 0;
    String realPath = getServletContext().getRealPath("/");
    result = this.contractBackCostService.exportBackCosts(realPath, isAllBackCost, sign, userId, userIds, exportBackCostForm);
    if (result) success = 1;
    return new ModelAndView(new RedirectView("./contractBackCost.do?action=preExportBackCost&sign=" + sign + "&result=" + success));
  }

  public void uploadExportFile(HttpServletRequest request, HttpServletResponse response)
  {
    Integer userId = (Integer)request.getSession().getAttribute("userId");
    String realPath = getServletContext().getRealPath("/");
    String basePath = realPath + "upload" + System.getProperty("file.separator") + "temp";
    String path = basePath + System.getProperty("file.separator") + "contractBackCost" + userId + ".xls";
    try
    {
      File file = new File(path);

      String filename = file.getName();

      String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

      InputStream fis = new BufferedInputStream(new FileInputStream(path));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();

      response.reset();

      response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
      response.addHeader("Content-Length", file.length()+"");
      OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/octet-stream");
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception
  {
    binder.registerCustomEditor(Date.class, new DatePropertyEditor());
    binder.registerCustomEditor(BigDecimal.class, new BigDecimalPropertyEditor());
  }
}